﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using ViazyNetCore;

namespace System.Security.Claims
{
    public static class ClaimsIdentityExtensions
    {
        /// <summary>
        /// 获取claim 值
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="claimType"></param>
        /// <returns></returns>
        public static string GetFirstValue(this ClaimsPrincipal claims, string claimType)
        {
            return claims.FindFirst(claimType)?.Value;
        }

        /// <summary>
        /// 获取当前登录用户的Id（ids4用户主键guid）。
        /// </summary>
        /// <param name="claims">当前用户接口实例。</param>
        /// <returns>返回用户Id，如果未登录则返回null。</returns>
        public static long GetUserId(this ClaimsPrincipal claims)
        {
            //ids4用户的唯一标识符
            var userid = claims.GetFirstValue(JwtClaimTypes.SessionId);
            return userid?.ParseTo<long>() ?? 0;
        }
        public static string FindClaimValue(this ICurrentUser currentUser, string claimType)
        {
            return currentUser.FindClaim(claimType)?.Value;
        }

        public static T FindClaimValue<T>(this ICurrentUser currentUser, string claimType)
            where T : struct
        {
            var value = currentUser.FindClaimValue(claimType);
            if (value == null)
            {
                return default;
            }

            return value.To<T>();
        }

        public static long FindTenantId([NotNull] this ClaimsPrincipal principal)
        {
            Check.NotNull(principal, nameof(principal));

            var tenantIdOrNull = principal.Claims?.FirstOrDefault(c => c.Type == JwtClaimTypes.TenantId);
            if (tenantIdOrNull == null || tenantIdOrNull.Value.IsNullOrWhiteSpace())
            {
                return 0;
            }

            return tenantIdOrNull?.ParseTo<long>() ?? 0;
        }

    }
}
